package com.myccb.app.view.activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.myccb.app.AppStatus;
import com.myccb.app.R;
import com.myccb.app.base.RequestManager;
import com.myccb.app.base.BaseActivity;
import com.myccb.app.widget.CommonDialog;
import com.myccb.app.widget.LoadingCountdownDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

public class LoginActivity extends BaseActivity {

    private TextView loginBtn;
    private EditText et_password;
    private TextView IDNumView;

    private String IDNum;
    private String password;

    private LoadingCountdownDialog loadingCountdownDialog;
    private CommonDialog errMsgDialog;
    private boolean loginSuccess;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!appStatus.isSaveUserInfo()){
            Intent intent = new Intent(LoginActivity.this,FirstLoginActivity.class);
            startActivity(intent);
            finish();
            //overridePendingTransition(R.anim.slide_in_right, android.R.anim.fade_out);
        }
        else {
            setContentView(R.layout.activity_login);
            setStatusBarColor(R.color.Grey1100);
            initView();
            initData();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppStatus.isLogin){
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
    }

    private void initView(){
        loginBtn=findViewById(R.id.login_btn);
        et_password=findViewById(R.id.edittext_password);
        IDNumView=findViewById(R.id.IDNum_textview);

        et_password.addTextChangedListener(new LoginTextWatcher());

        loginBtn.setEnabled(false);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                password=et_password.getText().toString();
                new LoginTask().execute();
            }
        });

        ImageView closeBtn=findViewById(R.id.login_activity_close);
        closeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent();
                intent.putExtra("status","close");
                setResult(2, intent);
                finish();
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });
        TextView changeUser=findViewById(R.id.login_activity_changeuser);
        changeUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,FirstLoginActivity.class);
                startActivity(intent);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            }
        });
        TextView newUser=findViewById(R.id.login_activity_newuser);
        newUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this,RegisterActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, android.R.anim.fade_out);
            }
        });

        loadingCountdownDialog=new LoadingCountdownDialog(this);
        errMsgDialog=new CommonDialog(this);
    }
    private void initData(){
        IDNum=appStatus.getSavedIDNum();
        IDNumView.setText(IDNum.substring(0,4)+"***"+IDNum.substring(IDNum.length()-4,IDNum.length()));
    }

    class LoginTextWatcher implements TextWatcher{
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (et_password.getText()==null){
                loginBtn.setEnabled(false);
                return;
            }
            if (et_password.getText().toString().length()<6){
                loginBtn.setEnabled(false);
                return;
            }
            loginBtn.setEnabled(true);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    class LoginTask extends AsyncTask<Void, Void, Integer> {
        @Override
        protected void onPreExecute() {
            loadingCountdownDialog.show(30);
        }

        @Override
        protected Integer doInBackground(Void... voids) {
            int code=0;
            HashMap<String,String> postParams=new HashMap<>();
            postParams.put("action","login");
            //postParams.put("vcode",vcode);
            postParams.put("IDNum",IDNum);
            postParams.put("password",password);

            String result= RequestManager.getInstance(getApplicationContext()).requestSyn("login.php",RequestManager.TYPE_POST_FORM,postParams);
            
            Log.d("login",result);

            JSONObject jb = null;
            try {
                jb = new JSONObject(result);
                int status=jb.getInt("status");
                if(status==0){
                    loginSuccess=false;
                    code=jb.getInt("code");
                    //result=""+code;
                }
                else if (status==1){
                    loginSuccess=true;
                    jb=jb.getJSONObject("result");
                    //userName=jb.getString("userName");
                    IDNum=jb.getString("IDNum");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return code;
        }
        @Override
        protected void onPostExecute(Integer code) {
            loadingCountdownDialog.dismiss();
            if (loginSuccess){
                //saveData();
                AppStatus.isLogin=true;
                SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                Date curDate =  new Date(System.currentTimeMillis());
                AppStatus.lastLoginTime=formatter.format(curDate);
                Intent intent=new Intent();
                intent.putExtra("status","success");
                setResult(2, intent);
                finish();
            }
            else {
                showLoginError(code);
            }
        }
    }
    private void showLoginError(int code){
        switch (code){
            case 2:
                errMsgDialog.showMessage("账户不存在！请选择切换用户后重新尝试登录","错误代码:"+code);
                break;
            case 3:
                errMsgDialog.showMessage("密码错误！请重新输入密码","错误代码:"+code);
                et_password.setText("");
                break;
        }
    }
}
